const jwt = require("jsonwebtoken");
const md5 = require("md5");
const { v4: uuidv4 } = require("uuid");

const multer = require("multer");
const path = require("path");

// 格式化要响应的数据
// {
//     "code" : code,
//     "msg" : "",
//     "data" : data
// }
module.exports.formatResponse = function (code, msg, data) {
  return {
    code: code,
    msg: msg,
    data: data,
  };
};

module.exports.analysisToken = function (token) {
  return jwt.verify(token.split(" ")[1], md5(process.env.JWT_SECRET));
};

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, "../public/static/images"));
  },
  filename: function (req, file, cb) {
    // 获取后缀名
    const extname = path.extname(file.originalname);
    // 构建新的名字
    const newName = uuidv4() + extname;
    cb(null, newName);
  },
});

module.exports.uploading = multer({
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024,
    // files: 1,
  },
});
